// Copyright (c) 2023 Presto Labs Pte. Ltd.
// Author: ziyan
#include "coin2/exchange/base/feed/ws/bittrex_connection.h"

#include "coin2/base/log.h"
#include "coin2/base/request/session_pool.h"
#include "coin2/exchange/base/api_util/api_signature.h"
#include "coin2/exchange/util/json_util.h"

namespace coin2::exchange::base::feed {
namespace impl {
using coin2::base::request::GetHttpsContent;

BittrexConnection::BittrexConnection(
    const WsConnectionConfig& config,
    std::function<void()> fail_callback,
    executor::LiveAsyncExecutor* exec,
    RequestGenerator* request_generator,
    std::shared_ptr<LatencyExtractor> latency_extractor,
    bool enable_telemetry)
    : WsConnection(
          config,
          fail_callback,
          exec,
          request_generator,
          latency_extractor,
          enable_telemetry) {}

BittrexConnection::~BittrexConnection() {}

void BittrexConnection::Run(boost::asio::yield_context yield) {
  std::string full_path = GetFullPath();
  WsConnection::Run(yield, config_.url.host, config_.url.port, full_path);
}


std::string BittrexConnection::GetFullPath(){
  auto connection_info = GetHttpsContent(config_.url.host, "/signalr/negotiate");
  rapidjson::Document document;
  document.Parse<rapidjson::kParseNumbersAsStringsFlag>(connection_info.data());
  if (document.HasParseError()) {
    throw std::runtime_error(std::string("JSON parse error: ") + GetParseError_En(document.GetParseError()));
  }
  std::string connection_token = document["ConnectionToken"].GetString();
  std::string url = document["Url"].GetString();
  std::string full_path = url + "/connect?transport=webSockets&connectionToken=" + ApiSignatureUtil::UrlEncode(connection_token);
  return full_path;
}

}  // namespace impl
}  // namespace coin2::exchange::base::feed